<template>
  <div class="md">
    <!-- 导航开始 -->
    <div
      v-for="(anchor,index) in t.titles"
      :key="index"
      :style="{ padding: `10px 0 10px ${anchor.indent * 20}px` }"
      @click="handleAnchorClick(anchor)"
    >
      <a style="cursor: pointer">{{ anchor.title }}</a>
    </div>
    <!-- 导航结束 -->

    <v-md-preview ref="preview" :text="text"> </v-md-preview>
  </div>
</template>

<script setup lang="ts">
import '@/assets/hljs.css'
import hljs from 'highlight.js'
import highlightjsLineNumbers from 'highlightjs-line-numbers2.js'
import ClipboardJS from 'clipboard'
import { onMounted, reactive, ref, watch } from 'vue'

const props = defineProps({
  text: String
})

// 预览组件ref
const preview = ref()

//摘自CSDN
/*生成复制按钮*/
//复制按钮
function codecopy_func() {
  const btn = `<div class="codecopy-btn" data-title="复制" data-clipboard-action="copy" data-clipboard-target="#code_index" onclick="let t=this;t.innerHTML='复制成功';setTimeout(function(){t.innerHTML='复制';},1500);">复制</div>`
  //获取所有的代码区域的pre元素节点
  const codecopys = (preview.value.$el as HTMLElement).getElementsByTagName('pre')
  //遍历DOM（pre节点）节点
  for (let i = 0; i < codecopys.length; i++) {
    //pre元素对象
    const codecopy = codecopys[i]

    //生成复制按钮
    const html_temp = btn.replace(/index/g, i + '')

    //找到code元素，并添加id属性，id的值和复制按钮的属性 data-clipboard-target 的值是一样的
    //判断pre标签内是否含有code标签，如是则执行

    if (codecopy.querySelector('code')?.nodeName == 'CODE') {
      codecopy.querySelector('code')!.id = 'code_' + i
      //将复制按钮追加至页面
      const html = codecopy.innerHTML + html_temp

      codecopy.innerHTML = html
    }
  }
  /*初始化复制功能*/
  const clipboardJs = new ClipboardJS('.codecopy-btn') //注意：ClipboardJS替代了Clipboard

  /*复制失败事件*/
  clipboardJs.on('error', function (e) {
    console.log(e)
  })
}

onMounted(() => {
  getAnchors()
  // 代码高亮
  hljs.highlightAll()
  highlightjsLineNumbers.init(hljs) //需要将 highlight.js 传入进行方法替换
  codecopy_func()
  // @ts-ignore
  hljs.initLineNumbersOnLoad()

})

// 适配axios
watch(
  () => props.text,
  // (to, from) => {
  () => {
    setTimeout(() => {
      getAnchors()
      // 代码高亮
      hljs.highlightAll()
      highlightjsLineNumbers.init(hljs) //需要将 highlight.js 传入进行方法替换
      codecopy_func()
      // @ts-ignore
      hljs.initLineNumbersOnLoad()
     
    }, 0)
  },
  { deep: true }
)

const t = reactive({
  titles: [] as Array<{ title: string; lineIndex: string; indent: number }>
})

// 获取导航
function getAnchors() {
  const anchors = (preview.value.$el as Element).querySelectorAll('h1,h2,h3,h4,h5,h6')

  const titles = Array.from(anchors).filter((title: any) => !!title.innerText.trim())
  if (!titles.length) {
    t.titles = []
    return
  }

  const hTags = Array.from(new Set(titles.map((title) => title.tagName))).sort()
  t.titles = titles.map((el: any) => ({
    title: el.innerText,
    lineIndex: el.getAttribute('data-v-md-line'),
    indent: hTags.indexOf(el.tagName)
  }))
console.log( t.titles);

 
}

// 点击导航
function handleAnchorClick(anchor: { title: string; lineIndex: string; indent: number }) {
  const { lineIndex } = anchor
  const heading = preview.value.$el.querySelector(`[data-v-md-line="${lineIndex}"]`)
  if (heading) {
    preview.value.scrollToTarget({
      target: heading,
      scrollContainer: window,
      top: 60
    })
  }
}
</script>

<style scoped>
.md {
  position: relative;
}
</style>
